package com.tanx.validator;

import com.tanx.dto.init.InitFormDto;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 * Created by 唐旭 on 2015/10/10.
 */
@Component
public class InitFormDtoValidator implements Validator {
    @Override
    public boolean supports(Class<?> aClass) {
        return InitFormDto.class.equals(aClass);
    }

    @Override
    public void validate(Object target, Errors errors) {
        InitFormDto formDto = (InitFormDto) target;
        ValidationUtils.rejectIfEmpty(errors, "name", null, "名称不能为空");
        validateUserName(formDto.getUsername(), errors);
        validatePassword(formDto.getPassword(), errors);
    }

    private void validatePassword(String password, Errors errors) {
        validateFieldLength(password, 20, "password", "密码", errors);
    }

    private void validateUserName(String username, Errors errors) {
        validateFieldLength(username, 20, "username", "用户名", errors);
    }

    private void validateFieldLength(String target, int length, String fieldName,
                                     String label, Errors errors) {
        ValidationUtils.rejectIfEmpty(errors, fieldName, null, label + "不能为空");

        if (target.length() > length) {
            errors.rejectValue(fieldName, null, label + "长度不能超过" + length);
        }
    }
}
